<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';


    if(!IsValidSession())
    {
        header('Location: login.php?page=add-new-user');
        exit();
    }
    else
    {
        RefreshSession();
    }

	$user = GetCurrentUserAccessLevel();
	
    //Check user access
    if($user != $DIRECTOR && $user != $ADMIN && $user != $REGISTRAR)
    {
        header('Location: login.php?page=add-new-student&error=To access to the create new student page, please log in as a registrar director or admin&logout=1');
        exit();
    }
	
    if($_POST['firstName'] == "" || $_POST['program'] == "" ||
	$_POST['lastName'] == "" || $_POST['dob'] == "" ||
	$_POST['sex'] == "")
    {
	$_SESSION['login_error'] = 'First Name, Last Name, Date of Birth, Sex and Program are required. Please try again.';
	header("Location: add-new-student.php");
	exit();
    }

    $link = connect_db();
    $query = "SELECT `UserId` FROM `User` WHERE `UserId` LIKE 'ST%' ORDER BY  `User`.`UserId` DESC;";
    $result = mysql_query($query,$link);
    $last_user = mysql_fetch_array($result,MYSQL_BOTH);
    $last_user = substr($last_user['UserId'],2);
    $new_user = str_pad($last_user+1,6,'0',STR_PAD_LEFT);

    $hash = gen_passwd_hash($_POST['firstName']);

    $query = "INSERT INTO `User` (`UserId`,
                                  `UserName`,
                                  `Password`,
                                  `PrivilegeLevel`,
                                  `EmailAddress`,
                                  `FirstName`,
                                  `MiddleName`,
                                  `LastName`,
                                  `Active`) VALUES
                                  ('ST".$new_user."',
                                   'ST".$new_user."',
                                   '".$hash."',
                                   '1',
                                   '".$_POST['emailAddress']."',
                                   '".$_POST['firstName']."',
                                   '".$_POST['middleName']."',
                                   '".$_POST['lastName']."',
                                   '1');";

    $result = mysql_query($query,$link);
	
	// Convert displayed DOB date style into Date style for database insert
	list($dobDay, $dobMonth, $dobYear) = split ("/", $_POST['dob']);
	$insertDOB = $dobYear."-".$dobMonth."-".$dobDay;
	// old date insert -> '".date('Y-m-d', strtotime($_POST['dob']))."', // strtotime fails when day is higher than 12

    $query = "INSERT INTO `Student` (`ID`,
									 `SchoolID`,
                                     `NMC_ID`,
                                     `Hometown`,
                                     `DOB`,
                                     `Sex`,
									 `PhoneNumber`,
                                     `Address`,
                                     `City`,
                                     `Region`,
                                     `PostalAddress`,
                                     `Country`,
                                     `programID`)
                             VALUES('ST".$new_user."',
                                    '".$_POST['schoolid']."',
									'".$_POST['nmcid']."',
                                    '".$_POST['hometown']."',
                                    '$insertDOB',
                                    '".$_POST['sex']."',
									'".$_POST['phoneNumber']."',
                                    '".$_POST['address']."',
                                    '".$_POST['city']."',
                                    '".$_POST['region']."',
                                    '".$_POST['postalCode']."',
                                    '".$_POST['country']."',
                                    '".$_POST['program']."');";
    
    
    $result = mysql_query($query,$link);
	
	if(!$result)
	{
		echo 'Error when inserting into student.<br />'.mysql_error();	
	}

    //Get fees associated with program and insert into DB.
    $query = "SELECT `ApplicationFee`, `InterviewFee` FROM `Program` WHERE `ProgramID` = '".$_POST['program']."';";
    $result = mysql_query($query,$link);
    $fees = mysql_fetch_array($result,MYSQL_BOTH);

    $query = "INSERT INTO `FeeLedger` (`StudentID`,
                                       `Date`,
                                       `Type`,
                                       `Amount`,
                                       `ProcessingUser`)
                               VALUES ('ST".$new_user."',
                                       '".date('Y-m-d H:i:s')."',
                                       '5',
                                       '".$fees['ApplicationFee']."',
                                       '".GetSessionUser()."');";
    $result = mysql_query($query,$link);

    $query = "INSERT INTO `FeeLedger` (`StudentID`,
                                       `Date`,
                                       `Type`,
                                       `Amount`,
                                       `ProcessingUser`)
                               VALUES ('ST".$new_user."',
                                       '".date('Y-m-d H:i:s')."',
                                       '7',
                                       '".$fees['InterviewFee']."',
                                       '".GetSessionUser()."');";
    $result = mysql_query($query,$link);

    addLogEntry('User', 'Added student: ST'.$new_user);
    
    masterpage("Add New Student");
    print <<<HTML
    <table>
        <tr><th class="tableTitle">Student Successfully Added</th></tr>
        <form name="fees" action="process-payment.php" method="post">
        <input type="hidden" name="StudentID" value="ST$new_user">
        <tr><th align="center"><a href="javascript:document.fees.submit();">Click to View Fees</a></th></tr>
        <tr><td align="center"><a href="index.php">Return to Homepage</a></td></tr>
        </form>
    </table>
HTML;

    endmasterpage();
?>
